<template>
  <div class="login-page">
    <!-- 导航栏 -->
    <van-nav-bar title="面经注册" />

    <!-- 表单 -->
    <!-- submit会在校验完成后，再点击提交或者按回车才会触发 -->
    <van-form @submit="onSubmit">
      <!-- 输入框 -->
      <!-- rules就是vant提供的给输入框做校验的地方 -->
      <!-- 在这里可以写一些校验的规则 -->
      <van-field
        v-model="user.username"
        label="用户名"
        placeholder="请输入用户名"
        :rules="rules.username"
      />
      <van-field
        v-model="user.password"
        type="password"
        label="密码"
        placeholder="密码"
        :rules="rules.password"
      />
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit"
          >注册</van-button
        >
      </div>
    </van-form>
    <router-link class="link" to="/login">有账号,去登录</router-link>
  </div>
</template>

<script>
// 导入接口
import { registerAPI } from '@/api/user'
export default {
  name: 'login-page',
  data () {
    return {
      user: {
        username: '',
        password: ''
      },
      // 规则对象
      rules: {
        username: [
          { required: true, message: '请填写用户名' },
          { pattern: /^\w{5,}$/, message: '账号至少5位' }
        ],
        password: [
          { required: true, message: '请填写密码' },
          { pattern: /^\w{6,}$/, message: '密码至少6位' }
        ]
      }
    }
  },
  methods: {
    async onSubmit () {
      try {
        // 当这个方法被调用，绝对校验全部通过
        // 发请求做注册
        await registerAPI({
          username: this.user.username,
          password: this.user.password
        })
        this.$toast('注册成功！')
        this.$router.push('/login')
      } catch {}
    }
  }
}
</script>

<style lang="less" scoped>
.link {
  color: #069;
  font-size: 12px;
  padding-right: 20px;
  float: right;
}
</style>
